package com.indusfo.spc.controller;


import com.indusfo.spc.pojo.Dep;
import com.indusfo.spc.service.DepService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;


//部门控制层
@Controller
@RequestMapping(value = "/service/dep")
public class DepController {


  @Autowired
  private DepService deptService;
/*
  增加
  */
  @RequestMapping(value = "/insertDep")
  @ResponseBody
  public JSONObject creatDepts(Dep dep) {
    JSONObject json = deptService.creatDepts(dep);
    return json;

  }

  /*
  增加
  */
  @RequestMapping(value = "/updateDep")
  @ResponseBody
  public JSONObject updateDep(Dep dep) {
    JSONObject json = deptService.creatDepts(dep);
    return json;

  }


/*
  删除
  */
  @RequestMapping(value = "/deleteDep")
  @ResponseBody
  public JSONObject deleteDepts(Dep dep) {
    JSONObject json = deptService.deleteDepts(dep);
    return json;

  }


  /*
  部门的树
  */
  @RequestMapping(value = "/treeDep")
  @ResponseBody
  public JSONObject treeDep(Dep dep) {
    JSONObject jsonObject = new JSONObject();
    List<XTreeNode> tree = null;
    try {
      List<XTreeNode> nodes = new ArrayList<>();
      List<Dep> deps =  deptService.DeptZtrees(dep);
      if(null != dep.getFlag()){
        XTreeNode xTreeNode = new XTreeNode();
        Dep dep1 = new Dep();
        dep1.setDepId(0);
        dep1.setDepPid(0);
        dep1.setDepName("全部");

        xTreeNode.setId(dep1.getDepId());
        xTreeNode.setpId(dep1.getDepPid() == 0 ? null : dep1.getDepPid());
        xTreeNode.setOpen(true);
        xTreeNode.setTitle(dep1.getDepName());
        deps.add(0,dep1);
      }
      for(Dep _D : deps){
        XTreeNode node = new XTreeNode();
        node.setId(_D.getDepId());
        node.setpId((_D.getDepPid()==null || _D.getDepPid() == 0)? null : _D.getDepPid());
        node.setOpen(true);
        node.setTitle(_D.getDepName());
        node.setCode(_D.getDepCode());
        nodes.add(node);
      }
      if(null != dep.getFlag() && dep.getFlag() >0 ){
        List<XTreeNode> aBoolean = new XTreeUtil().getBoolean(dep.getFlag(), nodes);
        //当页面初始化的时候为树的第一个默认是点亮的状态
        tree = XCommonUtil.getTree(aBoolean, null);
      }else{
        tree = XCommonUtil.getTree(nodes, null);
        tree.get(0).setSelected(true);
      }
      return JSONObject.oK(tree);
    }catch (Exception e){
      e.printStackTrace();
      jsonObject.setStatus(JSONObject.ERROR);
      jsonObject.setMsg(e.getMessage());
      return jsonObject;
    }
  }


}
